import React, { useState } from 'react'
import { Button, Tree, Select, DatePicker, Form, Input, Breadcrumb, Dropdown, message, Space, Modal, Table, Pagination, Drawer, Row, Col } from 'antd';
import { QuestionOutlined, MailOutlined, MessageOutlined, LoginOutlined, PhoneOutlined, ClockCircleOutlined, SkinOutlined, SmileOutlined, DownOutlined, SettingOutlined, EyeOutlined, UserOutlined, HomeOutlined, StarOutlined } from '@ant-design/icons';
import { getAllUserInfoApi, getDeptApi, addUserApi, updateUserInfoApi, delUserApi } from '../../apis/users'
import { getAllRoleApi, delRoleApi } from '../../apis/role'
import { sexConvert, statusConvert, roleNameConvertToRoleId, deptNameConvertToDeptId } from '../../utils/global';
import useForceUpdate from '../../hooks/useForceUpdate';
import FormItem from 'antd/es/form/FormItem';

const treeData = [
  {
    title: 'parent 1',
    key: '0-0',
    children: [
      {
        title: 'parent 1-0',
        key: '0-0-0',
        disabled: true,
        children: [
          {
            title: 'leaf',
            key: '0-0-0-0',
            disableCheckbox: true,
          },
          {
            title: 'leaf',
            key: '0-0-0-1',
          },
        ],
      },
      {
        title: 'parent 1-1',
        key: '0-0-1',
        children: [
          {
            title: (
              <span
                style={{
                  color: '#1890ff',
                }}
              >
                sss
              </span>
            ),
            key: '0-0-1-0',
          },
        ],
      },
    ],
  },
];

const { confirm } = Modal;
export default function User() {
  const forceUpdate = useForceUpdate()
  const [curRole, setCurRole] = useState([])
  //table数据
  const [tableData, setTableData] = useState([]);
  //删除用户
  const [delUserName, setDelUserName] = useState('')
  const [delDataId, setDelDataId] = useState([])
  //时间选择器
  const { RangePicker } = DatePicker
  //分页
  const [totalPage, setTotalPage] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  //单人信息模态框
  const [isUserInfoOpen, setIsUserInfoOpen] = useState(false);
  //右侧编辑弹出框
  const [openEdit, setOpenEdit] = useState(false);
  const [drawerTitle, setDrawerTitle] = useState('')
  //右侧查看弹出框
  const [checkEdit, setCheckEdit] = useState(false);
  //部门
  const [dept, setDept] = useState([]);
  //角色
  const [role, setRole] = useState([]);
  //表单
  const FormRef = React.useRef(null)
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const columns = [
    {
      title: '角色',
      dataIndex: 'roleName',
    },
    {
      title: '描述',
      key: 'remark',
      dataIndex: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      defaultSortOrder: 'descend',
      sorter: (a, b) => a.createTime - b.createTime,
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      defaultSortOrder: 'descend',
      sorter: (a, b) => a.modifyTime - b.modifyTime,
    },
    {
      title: '操作',
      key: 'action',
      render: (item) => (
        <Space>
          <SettingOutlined style={{ color: '#1890ff' }} onClick={() => editUser(item)} />
          <EyeOutlined style={{ color: '#42B983' }} onClick={() => checkUser(item)} />
        </Space>
      ),
    },
  ];
  React.useEffect(() => {
    //发接口获取所有角色数据
    getAllRole()
    //获取所有部门
    // getDeptApi()
    //   .then(res => {
    //     // console.log('getDeptApi', res.rows.children);
    //     const deptArr = res.rows.children
    //     setDept(deptArr)
    //   })

  }, [])
  //获取所有用户数据
  // function getAllUserInfo(params) {
  //   getAllUserInfoApi(params)
  //     .then(res => {
  //       // console.log('getAllUserInfoApi', res);
  //       setTableData(res.rows)
  //       setTotalPage(res.total)
  //     })
  // }
  //更多操作菜单
  const items = [
    {
      label: '密码重置',
      key: 'resetPwd'
    },
    {
      label: '导出Excel',
      key: 'exportExcel'
    }
  ];
  //搜索
  const doSearch = (values) => {
    // console.log('查询', values);
    let searchArr = {}
    if (values.roleName) {
      searchArr.roleName = values.roleName
    } else if (values.rangePicker) {
      searchArr.createTimeFrom = values.rangePicker[0].$y - values.rangePicker[0].$M - values.rangePicker[0].$D
      searchArr.createTimeTo = values.rangePicker[1].$y - values.rangePicker[1].$M - values.rangePicker[1].$D
    }
    console.log('查询', searchArr);

    getAllRoleApi(searchArr)
  };
  //编辑弹窗提交验证失败
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const onReset = () => {
    form.resetFields();
  };
  //更多操作
  const handleMenuClick = (e) => {
    // console.log('click', e.key);
    switch (e.key) {
      case 'resetPwd':
        console.log('密码重置');
        break;
      case 'exportExcel':
        console.log('导出Excel');
        break;
      default:
        break;
    }
  };
  const menuProps = {
    items,
    onClick: handleMenuClick,
  };
  //展示列表
  //选中用户
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('selectedRows: ', selectedRows);
      let delNameArr = []
      delNameArr = selectedRows.map(item => {
        return item.roleName
      })
      delNameArr = showDelName(delNameArr)
      // console.log('选中用户名字', delNameArr);
      setDelUserName(delNameArr)
      let delIdArr = []
      delIdArr = selectedRows.map(item => {
        return item.roleId
      })
      console.log('选中用户id', delIdArr);
      setDelDataId(delIdArr)
    },
  };
  //处理删除用户名字格式
  function showDelName(delNameArr) {
    let showName = ''
    delNameArr.forEach(item => {
      // console.log('item',item);
      if (item) {
        showName += item + ','
      }
    })
    // console.log('showName',showName);
    return showName.substring(0, showName.length - 1);
  }
  //编辑用户弹窗
  function editUser(params) {
    // console.log('editUser', params);
    //存到当前用户
    setCurRole(params)
    //当开右侧编辑弹出框
    setOpenEdit(true)
    setDrawerTitle('修改角色')
  }
  //获取角色数据
  function getAllRole(params) {
    getAllRoleApi(params)
      .then(res => {
        console.log('getAllRoleApi', res);
        setRole(res.rows)
        setTableData(res.rows)
        setTotalPage(res.total)
      })
  }
  const onClose = () => {
    setOpenEdit(false);
    editForm.resetFields()
  };
  //编辑弹窗提交
  const onFinish = (values) => {
    // console.log('success:', values);
    //新增
    if (drawerTitle == '新增角色') {
      // console.log('新增用户', values);
      const addObject = {
        username: values.username,
        password: values.password,
        email: values.email,
        mobile: values.mobile,
        roleId: values.roleName,
        deptId: values.deptName,
        status: values.status,
        ssex: values.ssex
      }
      //发接口
      addUserApi(addObject)
        .then(() => {
          message.success('新增成功，初始密码为1234qwer')
          setOpenEdit(false)//关闭弹窗
          getAllUserInfo({ pageNum: 1 })//刷新页面
          forceUpdate()
          //重置表单
          editForm.resetFields()
        })
    }
    //修改
    if (drawerTitle == '修改角色') {
      // console.log('修改用户', values);
      //角色转换为id
      const addRole = convertRoleNameToId(values.roleName)
      //部门转换为id
      const addDept = convertDeptNameToId(values.deptName)
      const editObject = {
        username: values.username,
        email: values.email,
        mobile: values.mobile,
        status: values.status,
        ssex: values.ssex,
        roleId: addRole,
        userId: curRole.userId,
        deptId: addDept
      }
      // console.log(editObject);
      // 发接口
      updateUserInfoApi(editObject)
        .then(() => {
          message.success('修改角色成功')
          setOpenEdit(false)//关闭弹窗
          getAllUserInfo({ pageNum: 1 })//刷新页面
          editForm.resetFields()//重置表单
        })
    }
  }
  //角色转换为id
  function convertRoleNameToId(roleName) {
    if (typeof (roleName) == 'string') {
      return roleNameConvertToRoleId(roleName)
    } else {
      return roleName.map(item => {
        if (typeof (item) == 'string') {
          item = roleNameConvertToRoleId(item)
        }
        return item
      })
    }
  }
  //部门转换为id
  function convertDeptNameToId(deptName) {
    if (typeof (deptName) == 'string') {
      return deptNameConvertToDeptId(deptName)
    } else {
      return deptName
    }
  }
  //查看角色资料
  function checkUser(params) {
    console.log('checkUser', params);
    //打开模态框
    setCheckEdit(true)
    setCurRole(params)
  }
  const checkUserCancel = () => {
    setIsUserInfoOpen(false);
  };
  //翻页
  function onChange(pageNum, pageSize) {
    // console.log(pageNum, pageSize)
    setPageSize(pageSize)
    getAllUserInfo({ pageNum, pageSize })
  }
  //新增用户按钮打开弹窗
  function doAdd() {
    // console.log('新增用户');
    setOpenEdit(true)
    setDrawerTitle('新增角色')
  }
  //判断新增？修改？
  React.useEffect(() => {
    if (openEdit) {//打开弹窗
      getAllRole()
      if (drawerTitle == '新增角色') {
        //初始化密码
        // console.log('初始化密码',FormRef.current);
        FormRef.current?.setFieldValue('password', '1234qwer')
      } else {
        //初始化表单
        console.log('curRole', curRole);
        FormRef.current?.setFieldsValue({
          ...curRole,
          // roleId: curRole.roleId.split(',')
        })
      }
    }
  }, [openEdit])
  //删除角色
  function doDel() {
    console.log('删除角色');
    //提示弹窗
    confirm({
      title: '您确定要删除以下角色吗?',
      icon: <QuestionOutlined />,
      content: delUserName,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        console.log('删除', delDataId);
        //发接口
        delRoleApi(delDataId)
          .then(() => {
            message.success('删除角色成功')
            getAllRole({ pageNum: 1 })//刷新页面
            forceUpdate()
          })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  //权限选择树形控件
  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
  };
  return (
    <div>
      {/* 面包屑 */}
      <div>
        <Breadcrumb>
          <Breadcrumb.Item>主页</Breadcrumb.Item>
          <Breadcrumb.Item>
            <a href="">系统管理</a>
          </Breadcrumb.Item>
          <Breadcrumb.Item style={{ color: 'black' }}>用户管理</Breadcrumb.Item>
        </Breadcrumb>
      </div>
      {/* 搜索 */}
      <div style={{ padding: 24 }}>
        <Form
          name="basic"
          layout='inline'
          onFinish={doSearch}
          autoComplete="off"
          form={form}
        >
          <Form.Item
            label="角色"
            name="roleName"
          >
            <Input placeholder='请输入查询的角色名' />
          </Form.Item>
          <Form.Item name="rangePicker" label="创建时间：">
            <RangePicker />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button htmlType="button" onClick={onReset}>重置</Button>
          </Form.Item>
        </Form>
      </div>
      {/* 新增、删除、更多操作按钮 */}
      <div>
        <Button style={{ border: '1px solid #1890ff' }} onClick={doAdd}>新增</Button>
        <Button style={{ margin: '0 10px' }} onClick={() => doDel()}>删除</Button>
        <Dropdown menu={menuProps}>
          <Button>
            <Space>
              更多操作
              <DownOutlined />
            </Space>
          </Button>
        </Dropdown>
      </div>
      {/* 展示列表table */}
      <div style={{ marginTop: 20 }}>
        <Table
          rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }}
          columns={columns}
          dataSource={tableData}
          rowKey="roleId"
          pagination={false}
        />
        <div style={{ textAlign: 'right', marginTop: 25 }}>
          <Pagination
            total={totalPage}
            showSizeChanger
            showQuickJumper
            onChange={onChange}
            showTotal={(total) => `显示1~${pageSize}条记录,共 ${total} 条记录`}
          />
        </div>
      </div>
      {/* 右侧编辑弹出框 */}
      <Drawer title={drawerTitle} placement="right"
        onClose={onClose} open={openEdit}
        size='large'
        closable={false}
        footer={
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button onClick={() => (FormRef.current).submit()} type="primary" >
              提交
            </Button>
          </Space>
        }
        footerStyle={{ textAlign: 'right' }}
      >
        <Form hideRequiredMark
          ref={FormRef}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          form={editForm}
          // requiredMark
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 30,
          }}
          layout="horizontal"
        >
          <Row gutter={10}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="角色名称："
                rules={[
                  {
                    required: true,
                    message: '请输入角色名称',
                  },
                ]}
              >
                <Input placeholder="请输入角色名称" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="remark"
                label="角色描述："
                rules={[
                  {
                    required: true,
                    message: '请输入角色描述',
                  },
                ]}
              >
                <Input.TextArea rows={4} placeholder="请输入描述内容" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <FormItem
                name="menuId"
                label="权限选择："
              >
                <Tree
                  checkable
                  defaultExpandedKeys={['0-0-0', '0-0-1']}
                  defaultSelectedKeys={['0-0-0', '0-0-1']}
                  defaultCheckedKeys={['0-0-0', '0-0-1']}
                  onSelect={onSelect}
                  onCheck={onCheck}
                  treeData={treeData}
                />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Drawer>
    </div>
  )
}
